package www.lagou.app;

import com.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 按照步骤实现 卡号：1122334455 向卡号 5544332211 转账5000元
 */
public class Test_Account {

    public static void main(String[] args) throws SQLException {
        //1、创建QueryRunner 对象
        QueryRunner qr = new QueryRunner();
        //2、获取连接
        Connection connection = DruidUtils.getConnection();
        //3、开启事务
        connection.setAutoCommit(false);  //关闭自定提交事务

        //4、执行查询语句 查看前者账户中金额是否大于5000
        String sql = "select balance from Account where card = ?";
        Double balance = qr.query(connection, sql, new ScalarHandler<>(), "1122334455");

        //5、判断金额是否大于5000
        if(balance<5000){
            System.out.println("余额不足，无法转账！");
            return;
        }

        //6、开始转账
        //1122334455 账户 减少五千大洋
        String sql1 = "UPDATE Account SET balance = balance - ? where card =? ";
        qr.update(connection,sql1,5000,"1122334455");

        //账户：5544332211 增加五千块
        String sql2 = "UPDATE Account SET balance = balance +? where card = ?";
         qr.update(connection, sql2, 5000, "55443332211");

         //7、处理交易记录
        //转出记录
        String sql3 = "insert into transaction values(?,?,?,?,?)";
        Object[] param ={null,"1122334455","转出",5000, DateUtils.getDateFormart()};
        qr.update(connection,sql3,param);

        //System.out.println(1/0);

        //转入操作
        String sql4 = "insert into transaction values(?,?,?,?,?)";
        Object[] param1 ={null,"55443332211","转入",5000, DateUtils.getDateFormart()};
        qr.update(connection,sql4,param1);

        //手动提交事务
        connection.commit();
        System.out.println("转账成功！");

        //发生异常进行回滚
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }
}
